﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using HtmlAgilityPack;
using System.Web.Script.Serialization;

namespace xuptlibsearch
{
    public partial class NewBook : System.Web.UI.Page
    {
        NewBookList Book = new NewBookList();
        Dictionary<string, TypeDictItem> TypeDict = new Dictionary<string, TypeDictItem>();
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Charset = "UTF-8";
            Response.ContentType = "text/json";
            TypeDict.Add("01", new TypeDictItem { Name = "电工技术", Code = "µç¹¤¼¼Êõ" });
            TypeDict.Add("02", new TypeDictItem { Name = "航空、航天", Code = "º½¿Õ¡¢º½Ìì" });
            TypeDict.Add("03", new TypeDictItem { Name = "化学工业", Code = "»¯Ñ§¹¤Òµ" });
            TypeDict.Add("04", new TypeDictItem { Name = "环境科学、安全科学", Code = "»·¾³¿ÆÑ§¡¢°²È«¿ÆÑ§" });
            TypeDict.Add("05", new TypeDictItem { Name = "机械、仪表工业", Code = "»úÐµ¡¢ÒÇ±í¹¤Òµ" });
            TypeDict.Add("06", new TypeDictItem { Name = "交通运输", Code = "½»Í¨ÔËÊä" });
            TypeDict.Add("07", new TypeDictItem { Name = "金属学与金属工艺", Code = "½ðÊôÑ§Óë½ðÊô¹¤ÒÕ" });
            TypeDict.Add("08", new TypeDictItem { Name = "经济", Code = "¾­¼Ã" });
            TypeDict.Add("09", new TypeDictItem { Name = "军事", Code = "¾üÊÂ" });
            TypeDict.Add("10", new TypeDictItem { Name = "历史、地理", Code = "ÀúÊ·¡¢µØÀí" });
            TypeDict.Add("11", new TypeDictItem { Name = "社会科学总论", Code = "Éç»á¿ÆÑ§×ÜÂÛ" });
            TypeDict.Add("12", new TypeDictItem { Name = "数理科学和化学", Code = "ÊýÀí¿ÆÑ§ºÍ»¯Ñ§" });
            TypeDict.Add("13", new TypeDictItem { Name = "天文学、地球科学", Code = "ÌìÎÄÑ§¡¢µØÇò¿ÆÑ§" });
            TypeDict.Add("14", new TypeDictItem { Name = "文化、科学、教育、体育", Code = "ÎÄ»¯¡¢¿ÆÑ§¡¢½ÌÓý¡¢ÌåÓý" });
            TypeDict.Add("15", new TypeDictItem { Name = "文学", Code = "ÎÄÑ§" });
            TypeDict.Add("16", new TypeDictItem { Name = "无线电电子学、电信技术", Code = "ÎÞÏßµçµç×ÓÑ§¡¢µçÐÅ¼¼Êõ" });
            TypeDict.Add("17", new TypeDictItem { Name = "一般工业技术", Code = "Ò»°ã¹¤Òµ¼¼Êõ" });
            TypeDict.Add("18", new TypeDictItem { Name = "医药、卫生", Code = "Ò½Ò©¡¢ÎÀÉú" });
            TypeDict.Add("19", new TypeDictItem { Name = "艺术", Code = "ÒÕÊõ" });
            TypeDict.Add("20", new TypeDictItem { Name = "语言、文字", Code = "ÓïÑÔ¡¢ÎÄ×Ö" });
            TypeDict.Add("21", new TypeDictItem { Name = "哲学、宗教", Code = "ÕÜÑ§¡¢×Ú½Ì" });
            TypeDict.Add("22", new TypeDictItem { Name = "政治、法律", Code = "ÕþÖÎ¡¢·¨ÂÉ" });
            TypeDict.Add("23", new TypeDictItem { Name = "自动化技术、计算机技术", Code = "×Ô¶¯»¯¼¼Êõ¡¢¼ÆËã»ú¼¼Êõ" });

            string type = Request.Params["type"];
            try
            {
                int n = Convert.ToInt32(type);
                if (n > 23 || n < 1)
                {
                    throw new ArgumentOutOfRangeException();
                }
            }
            catch
            {
                Response.Write("Type_Error");
                return;
            }
            string currentpage = Request.Params["page"];
            if(currentpage=="" || currentpage==null)
                currentpage="1";
            string size = Request.Params["size"];
            if(size=="" || size==null)
                size="10";
            string time = Request.Params["time"];
            if(time=="" || time==null)
                time="30";
            ReqServer(type, currentpage, size, time);
        }
        void ReqServer(string type, string currentpage, string size, string time)
        {
            string restr = "";
            try
            {
                string url = string.Format("http://222.24.3.7:8080/opac_two/newbook/queryOut.jsp?classname={0}&size={1}&nbpar1={2}&curpage={3}", TypeDict[type].Code, size, time, currentpage);
                WebRequest request = WebRequest.Create(url);
                WebResponse response = request.GetResponse();
                Stream stream = response.GetResponseStream();
                StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("GB2312"));
                restr = reader.ReadToEnd();
            }
            catch
            {
                Response.Write("Server_Error");
                return;
            }
            if (restr.Contains("目前没有该类新书！"))
            {
                Response.Write("null");
                return;
            }
            string tmp = "";
            restr = restr.Substring(restr.IndexOf("当前第"));
            tmp = restr.Substring(restr.IndexOf("条"));
            string pages = restr.Replace(tmp, "");
            HtmlDocument doc = new HtmlDocument();
            pages = pages.Replace("\n", "");
            pages = pages.Replace("\r", "");
            pages = pages.Replace("\t", "");
            pages = pages.Replace("<span >检索结果</span> —共", "");
            pages = pages.Replace("&nbsp;", "");
            doc.LoadHtml(pages);
            HtmlNode node = doc.DocumentNode;

            int CurrentPage = Convert.ToInt32(node.ChildNodes[1].InnerText);
            int Pages = Convert.ToInt32(node.ChildNodes[3].InnerText);
            int Amount = Convert.ToInt32(node.ChildNodes[5].InnerText);

            if (CurrentPage > Pages)
            {
                Response.Write("Out_Of_Range");
                return;
            }

            restr = restr.Substring(restr.IndexOf("<TR"));
            tmp = restr.Substring(restr.IndexOf("</table>"));
            restr = restr.Replace(tmp, "");

            Book.Amount = Amount;
            Book.CurrentPage = CurrentPage;
            Book.Pages = Pages;
            Book.TimeSpan = Convert.ToInt32(time);
            Book.Size = Convert.ToInt32(size);
            Book.Type = TypeDict[type].Name;
            
            ProcHTML(restr);
        }
        void ProcHTML(string HTML)
        {
            List<NewBookItem> Data = new List<NewBookItem>();
            HTML = HTML.Replace("\n", " ");
            HTML = HTML.Replace("\r", " ");
            HTML = HTML.Replace("\t", " ");
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(HTML);
            HtmlNodeCollection node = doc.DocumentNode.ChildNodes;

            for (int i = 0; i < node.Count; i += 2)
            {
                HtmlDocument tmp = new HtmlDocument();
                tmp.LoadHtml(node[i].InnerHtml);
                HtmlNodeCollection no = tmp.DocumentNode.ChildNodes;
                string Title = no[3].InnerText;
                string Link = no[3].InnerHtml;
                Link = Link.Substring(Link.IndexOf("sid=") + 4);
                string t = Link.Substring(Link.IndexOf("&"));
                Link = Link.Replace(t, "");
                string Author = no[5].InnerText.Replace(",&nbsp;","");
                string Pub = no[6].InnerText.Replace("&nbsp;", "");
                string PubTime = no[7].InnerText.Replace("&nbsp;", "");
                string Time = no[8].InnerText.Replace("&nbsp;", "");
                Data.Add(new NewBookItem
                {
                    ID = Link,
                    Title = Title,
                    Author = Author,
                    Pub = Pub,
                    PubTime = PubTime,
                    AddTime = Time
                });
            }
            Book.Item = Data;
            JavaScriptSerializer json = new JavaScriptSerializer();
            Response.Write(json.Serialize(Book));
        }
    }
}